package org.example.backend.web.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.backend.controller.DataResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;

/*
 * @Date 2024-10-09
 * @Author 28254
 * @ClassName MyAuthenticationEntryPoint
 * 处理未认证 的处理类
*/
@Component
public class MyAuthenticationEntryPoint  implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException{
        String localizedMessage = "需要完成身份验证才能访问此资源";
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(new DataResult(401,null,localizedMessage, Instant.now().toEpochMilli()));
        response.getWriter().write(result);
    }
}
